import Taro, {Component} from "@tarojs/taro";
import {View, Image, Text, Input, Button} from "@tarojs/components";
import {inject, observer} from '@tarojs/mobx'
import {IStoreProps} from '../../store/Stores'
import {getRuntime, isNumber} from '../../utils/common'

import './cash.less'

import icon_83 from "../../assets/img/common/icon_83.png";
import icon_84_on from "../../assets/img/icon_06_on.png";
import icon_84 from "../../assets/img/common/icon_84_on.png";
import icon_85 from "../../assets/img/common/icon_85.png";

interface IHomeProps extends IStoreProps {}

@inject("stores")
@observer
class Cash extends Component<IHomeProps> {
  constructor(props) {
    super(props)
  }

  state = {
    cashType:2, // 提现方式1：微信钱包 2：银行卡
    items: [],
    currentBankNo: null, // 银行卡ID
    cardName:'', // 银行卡姓名 ,
    cardNumber:'', // 银行卡号 ,
    bankCode:'', // 银行编码 ,
    amount: null, // 提现金额
    userCashRate: 0, // 提现手续费
    serviceMoney: {}, // 服务费
    userInfo: {}
  }

  componentWillMount(): void {
    Taro.setNavigationBarTitle({ title:'立即提现' })
    let userCashRate = parseFloat(this.$router.params.userCashRate) || 0
    let userInfo = getRuntime().getUserInfo()
    console.log(userCashRate)
    /*if(!userCashRate){
      getRuntime().showToast('提现手续费获取失败, 无法完成提现~')
      setTimeout(() => {
        getRuntime().navigateTo('/pages/mine/index')
      }, 3000)
    }*/
    let serviceMoney = (userInfo.commision * userCashRate).toFixed(2)
    this.setState({
      userInfo,
      serviceMoney,
      userCashRate
    })
    this.getUserCards()
    // this.getCashService()
  }

  handelRouter(url: string = '/pages/index/index'): void {
    getRuntime().navigateTo(url)
  }

  changeCashType(cashType:number){
    this.setState({
      cashType
    })
  }

 /* getCashService() {
    let { userStore } = this.props.stores
    userStore.getCashService({
      callback: res => {this.setState({ serviceMoney: res })}
    })
  }*/

  getUserCards() {
    let { userStore } = this.props.stores
    userStore.getUserCards({
      callback: res => {
        this.setState({
          items: res.items
        })
      }
    })
  }

  changeBank(item: number) {
    this.setState({
      currentBankNo: item.id,
      cardName: item.cardName,
      cardNumber: item.cardNumber,
      bankCode: item.bankCode,
    })
  }

  // 截取银行卡后四位
  getPartBankNo(bankNo: string){
    if(bankNo.length<5){ return bankNo }
    return bankNo.substr(-4)
  }

  setAmount() {
    let { userInfo, userCashRate } = this.state
    this.setState({
      amount: userInfo.commision,
      serviceMoney: (userInfo.commision*userCashRate).toFixed(2)
    })
  }

  inputChange(e) {
    let { userCashRate } = this.state
    let amount = e.detail.value
    if(!isNumber(amount)){ getRuntime().showToast('只能输入数字~'); return }
    this.setState({
      amount,
      serviceMoney: (amount*userCashRate).toFixed(2)
    })
  }

  // 提现
  submit() {
    let {amount,cardName,cardNumber,bankCode,userInfo,serviceMoney, userCashRate} = this.state
    if(!amount&&amount<=0){ getRuntime().showToast('请填写提现金额~');return }
    if(amount>userInfo.commision){ getRuntime().showToast('您的余额不足~');return }
    if(!cardName||!cardNumber||!bankCode){ getRuntime().showToast('请选择银行卡~');return; }
    let { userStore } = this.props.stores
    let cashInfo = {
      cashAmount: amount,
      cashServiceMoney: (amount * userCashRate).toFixed(2),
      cashType: '银行卡'
    }

    userStore.cash({
      form: {
        cardName,
        cardNumber,
        bankCode,
        amount,
        cashType: 1,
      },
      callback: res => {
        // console.log(res)
        getRuntime().wxPay(JSON.parse(res.payParams), () => {
          getRuntime().showToast('提现成功~')
          getRuntime().setStorage('cashInfo', cashInfo)
          setTimeout(() => {
            getRuntime().navigateTo('/pages/mine/cashSuccess')
          },2000)
        })
      }
    })
  }

  render() {
    let { cashType,items,currentBankNo,serviceMoney,userInfo,amount, userCashRate } = this.state
    let commision = userInfo.commision
    console.log(amount)
    return (
      <View className='my-my_cash_now'>
        <View className='header'>
          <View className='list-desc'>请输入提现金额（元）</View>
          <View className='input-group'>
            <Input className='from-input' name='amount' type='number'
                   onChange={this.inputChange.bind(this)} placeholderClass='placeholder_class' placeholder='￥0.00'
                   value={amount}
            />
          </View>
          {
            amount&&
            <View className='info'>
               额外扣除{serviceMoney}元手续费<Text className='color color-orange'>(费率{userCashRate*100}%)</Text>
            </View>
          }
          {
            !amount&&
            <View className='info'>
               当前收益余额{commision}元，<Text className='color' onClick={this.setAmount.bind(this)}>全部提现</Text>
            </View>
          }
        </View>

        <View className='type-item'>
          {/* <View className='item' onClick={this.changeCashType.bind(this, 1)}>
            <Image src={icon_83} className='type-icon'/>
            <View className='list-title'>微信钱包</View>
            {cashType===1&& <Image src={icon_84} className='check-icon'/>}
            {cashType!==1&& <Image src={icon_84_on} className='check-icon'/>}
          </View>*/}
          <View className='item' onClick={this.changeCashType.bind(this, 2)} >
            <Image src={icon_85} className='type-icon' />
            <View className='list-title'>银行卡</View>
            {/*{cashType===2&& <Image src={icon_84} className='check-icon'/>}
            {cashType!==2&& <Image src={icon_84_on} className='check-icon'/>}*/}
          </View>

          <View className={cashType===2 ? 'item-sub item-sub-on' : 'item-sub'}>
            {items&&
            items.map(item => {
              return(
                <View className='op' onClick={this.changeBank.bind(this, item)}>
                  <View className='list-title'>{item.bankName}（{this.getPartBankNo(item.cardNumber)}）</View>
                  {currentBankNo!==item.id&& <Image src={icon_84} className='check-icon' />}
                  {currentBankNo===item.id&& <Image src={icon_84_on} className='check-icon' />}
                </View>
              )
            })
            }
            <View className='op' onClick={this.handelRouter.bind(this,'/pages/mine/cardAdd')}>
              <View className='list-title'>+ 使用新卡提现</View>
            </View>
          </View>
        </View>
        <View className='from-wrap'>
          <Button formType='submit' className='circular-submit' onClick={this.submit.bind(this)}>确认提现</Button>
          <View className='circular-tip'>预计24小时内到账</View>
        </View>
      </View>
    )
  }
}

export default Cash
